package com.example.yls.demoa;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import org.w3c.dom.Text;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements IOnDataChangeListener {
    private ListView lvStu;
    private Button btnAdd;
    private ArrayList<Student> studentArrayList = new ArrayList<>();
    private StuAdapter adapter;
    private Button btnSearch;
    private EditText edtSearch;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViews();

       //initStudentArrayList();

        adapter = new StuAdapter(MainActivity.this, studentArrayList,MainActivity.this);
        readDataFromDB();

        lvStu.setAdapter(adapter);
    }

    /**
     * 从数据库读取学生列表
     */
    private void readDataFromDB() {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        String sql = "create table if not exists student (stuno varchar(20), name varchar(20), age int)";
        db.execSQL(sql);

        studentArrayList.clear();
        Cursor cursor = db.query("student", null,null,
                null,null,null,null,null);

        if(cursor != null && cursor.getCount() > 0){
            for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
                String stuno = cursor.getString(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);

                Student  student = new Student(stuno, name, age);
                studentArrayList.add(student);
            }
        }

        adapter.notifyDataSetChanged();

        cursor.close();
        db.close();
    }

    private void initStudentArrayList() {
        Student s1 = new Student("17001","kris wu", 18);
        Student s2 = new Student("17002","Team Wang", 28);
        Student s3 = new Student("17003","Gucci Mane", 38);
        Student s4 = new Student("17004","Migos", 48);

        addStudentToDB(s1);
        addStudentToDB(s2);
        addStudentToDB(s3);
        addStudentToDB(s4);


    }

    private void findViews() {
        lvStu = findViewById(R.id.lv_stu);
        btnAdd = findViewById(R.id.btn_add);
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, AddActivity.class);
                startActivityForResult(intent, 1001);
            }
        });
        edtSearch=findViewById(R.id.edt_search);
        btnSearch = findViewById(R.id.btn_search);
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String key =edtSearch.getText().toString();
                Log.e("aaa",key.getClass().toString());
                searchStudent(key);
            }
        });
    }



    private void searchStudent(String key) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);


        String where = "name like '%" + key +"%' OR stuno like '%" + key +"%' " +
                "OR age = " +"' "+ key+"' ";
        studentArrayList.clear();
        Cursor cursor = db.query("student",null,where,null,null,null,null);
        if(cursor != null && cursor.getCount() > 0){
            for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
                String stuno = cursor.getString(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);

                Student  student = new Student(stuno, name, age);
                studentArrayList.add(student);
            }
        }
        adapter.notifyDataSetChanged();

        cursor.close();
        db.close();
    }



    private void addStudentToDB(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        ContentValues values = new ContentValues();
        values.put("stuno", student.getStuno());
        values.put("name", student.getName());
        values.put("age", student.getAge());

        db.insert("student", null, values);//使用insert接口
        db.close();
        readDataFromDB();
    }


    public void del(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        //方法一：使用execSQL()方法 优点：可以看到sql代码 缺点：写起来麻烦
        /*String sql = "delete from student where stuno = '"+student.getStuno()+"'";
        db.execSQL(sql);
        db.close();
        readDataFromDB();*/


        //方法二：使用delete接口 优点：指定那个表
        /*String where = "stuno = '"+student.getStuno()+"'";
        db.delete("student",where,null);
        db.close();
        readDataFromDB();*/
        //方法三：使用delete接口 优点，指定哪个表，删除具体那个参数
        String where = "stuno=?";
        String[] argArray = {student.getStuno()};
        db.delete("student",where,argArray);
        db.close();
        readDataFromDB();
    }

    @Override
    public void intentDataToAddView(Student student) {
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, EditActivity.class);
        intent.putExtra("STUNO", student.getStuno());
        intent.putExtra("NAME", student.getName());
        intent.putExtra("AGE", student.getAge());
        startActivityForResult(intent, 1002);
    }
    //接收editActivity的返回值

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == 2001){
            String stuno = data.getStringExtra("STUNO");
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE", 0);

            Student student =  new Student(stuno, name, age);
            addStudentToDB(student);
        }else if(resultCode == 3001){
            String stuno = data.getStringExtra("STUNO");
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE", 0);

            Student student =  new Student(stuno, name, age);
            updateStudentToDB(student);
        }
    }

    private void updateStudentToDB(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        /** 第一种 组装语句
         String sql = "update student set name = '"+student.getName()+"'," +
         " age = "+student.getAge()+" where stuno = '"+student.getStuno()+"'";
         db.execSQL(sql);
         db.close();
         readDataFromDB();*/

        // 第二种方式 update
        ContentValues values = new ContentValues();
        values.put("name", student.getName());
        values.put("age", student.getAge());
        String where = "stuno = '"+student.getStuno()+"'";
        db.update("student", values, where, null);
        db.close();
        readDataFromDB();
    }
}

